﻿//  Copyright © 2009-2010 by Rhy A. Mednick
//  All rights reserved.
//  http://rhyduino.codeplex.com
//  
//  Redistribution and use in source and binary forms, with or without modification, 
//  are permitted provided that the following conditions are met:
//  
//  * Redistributions of source code must retain the above copyright notice, this list 
//    of conditions and the following disclaimer.
//  
//  * Redistributions in binary form must reproduce the above copyright notice, this 
//    list of conditions and the following disclaimer in the documentation and/or other 
//    materials provided with the distribution.
//  
//  * Neither the name of Rhy A. Mednick nor the names of its contributors may be used 
//    to endorse or promote products derived from this software without specific prior 
//    written permission.
//  
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
//  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
//  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
//  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
//  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
//  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
//  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
//  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using TracerX;

namespace Rhyduino
{
    ///<summary>
    ///  Class for managing the state of the digital pins.
    ///</summary>
    public class DigitalPins
    {
        #region Constructor(s)

        internal DigitalPins(Arduino arduino)
        {
            if (arduino == null) throw new ArgumentNullException("arduino");

            _digitalPins = new[]
                               {
                                   new DigitalPin(arduino, 2),
                                   new DigitalPin(arduino, 3),
                                   new DigitalPin(arduino, 4),
                                   new DigitalPin(arduino, 5),
                                   new DigitalPin(arduino, 6),
                                   new DigitalPin(arduino, 7),
                                   new DigitalPin(arduino, 8),
                                   new DigitalPin(arduino, 9),
                                   new DigitalPin(arduino, 10),
                                   new DigitalPin(arduino, 11),
                                   new DigitalPin(arduino, 12),
                                   new DigitalPin(arduino, 13)
                               };
        }

        #endregion

        #region Propertie(s)

        ///<summary>
        ///  Gets the pin information for the specified digital pin.
        ///</summary>
        ///<param name = "pinNumber">The digital pin number.</param>
        ///<exception cref = "InvalidOperationException">When the value specified for the pinNumber is not a valid pin number.</exception>
        public DigitalPin this[int pinNumber]
        {
            get
            {
                if (2 > pinNumber || pinNumber > 13)
                {
                    throw new InvalidOperationException("Index must be a value from 2-13.");
                }

                return _digitalPins[pinNumber - 2];
            }
        }

        #endregion

        #region Fields

        private readonly DigitalPin[] _digitalPins;

        #endregion

        #region Private Methods

        private void SetPinValue(int pinNumber, DigitalPinValue value)
        {
            _log.DebugFormat("Setting digital pin value: [{0}] = {1}", pinNumber, value);
            this[pinNumber].SetPinValue(value);
        }

        ///<summary>
        ///  We use this internally to set the value of the pins when we get a port report from the Arduino.
        ///  If we get a report from a pin that's not in input mode then we log the incident but don't change
        ///  the value internally.
        ///</summary>
        ///<param name = "portNumber">The port number.</param>
        ///<param name = "value">The value of the port.</param>
        ///<exception cref = "ArgumentOutOfRangeException">When the value specified for the port number is not valid.</exception>
        internal void SetPortValue(int portNumber, int value)
        {
            if (portNumber == 0)
            {
                for (var index = 0; index < 6; index++)
                {
                    var pinNumber = index + 2;
                    if (this[pinNumber].Mode == PinMode.Input)
                    {
                        // Is the value high for this pin?
                        var pinMask = 1 << pinNumber;
                        SetPinValue(pinNumber, (value & pinMask) == 0 ? DigitalPinValue.Low : DigitalPinValue.High);
                    }
                }
            }
            else if (portNumber == 1)
            {
                for (var index = 0; index < 7; index++)
                {
                    var pinNumber = index + 8;

                    if (this[pinNumber].Mode != PinMode.Input)
                    {
                        continue;
                    }

                    // Is the value high for this pin?
                    var pinMask = 1 << index;

                    SetPinValue(pinNumber, (value & pinMask) == 0 ? DigitalPinValue.Low : DigitalPinValue.High);
                }
            }
            else
            {
                throw new ArgumentOutOfRangeException("portNumber");
            }
        }

        #endregion

        private static readonly Logger _log = Logger.GetLogger("DigitalPins");
    }
}